package loader;

import image.bmp.BMPImage;
import image.header.BMPHeader;
import image.header.DIBHeader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import util.Log;

public class ImageLoader {
	public static final String TAG = "ImageLoader";
	public static BMPImage loadBMP(String filename) 
			throws IOException {
		BMPImage image = new BMPImage();
		FileInputStream in = null;
		try {
			File f = new File(filename);
			in = new FileInputStream(f);
			Log.log(TAG, "Filesize: " + (int)f.length());
			byte[] b = new byte[(int) f.length()];
			if (in.read(b, 0, (int) f.length()) < 0) {
				throw new IOException("Read in -1 byte.");			
			}
			ByteBuffer bb = ByteBuffer.wrap(b);
			bb.order(ByteOrder.LITTLE_ENDIAN);

			// Read in BMPHeader (14 bytes)
			BMPHeader bmpHeader = new BMPHeader();
			int headerSize = 14;
			byte[] headBit = new byte[headerSize];
			bb.get(headBit, 0, headerSize);
			bmpHeader.parse(headBit);
			Log.log(TAG, "BMP Header: \n" + bmpHeader.toString());
			
			// Read in DIBHeader
			DIBHeader dibHeader = new DIBHeader();
			int size = bb.getInt();
			byte[] dibBit = new byte[size];
			bb.get(dibBit, 0, size - 4);				// Lost 4 bytes (size)
			dibHeader.parse(size, dibBit);
			Log.log(TAG, "DIB Header: \n" + dibHeader.toString());
			
			// Read in color table
			// Only if there're space between the pixel map's head 
			// and DIBHeader' tail
			if (dibHeader.getSize() < bmpHeader.getPixelOffset() - 14) {
				int colorTableSize = bmpHeader.getPixelOffset() - 14 - dibHeader.getSize();
				byte[] colorTable = new byte[colorTableSize];
				bb.get(colorTable, 0, colorTableSize);
			}
			
			// Read in the bitmap (pixel map)
			int colorMapSize = dibHeader.getImageSizeWithPadding();
			byte[] colorMap = new byte[colorMapSize];
			Log.d(TAG, "Color map size: " + colorMapSize);
			bb.get(colorMap, 0, colorMapSize);
			
			image = new BMPImage(colorMap, bmpHeader, dibHeader);
			
		} catch(FileNotFoundException notfounde) {
			Log.log(TAG, "The file is missing, please check the path.");
		} catch(Exception e) {
			e.printStackTrace();
			Log.log(TAG, e.getMessage());
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return image;
	}
}
